import { defineStore } from "pinia";
import { store } from "@/store";
// state 返回数据类型
interface IRootUserInfo {
  menus: Menus[];
  username: string;
}
interface INewMenus {
  [index: number]: Menus;
}
export const useUserStore = defineStore("userInfo", {
  state(): IRootUserInfo {
    return {
      menus: [],
      username: "",
    };
  },
  getters: {
    getMenusConf(state) {
      const newMenus: INewMenus = {};
      state.menus.forEach((item) => {
        if (item.parentId === 0) {
          // 防止js报错
          newMenus[item.id] ??= {} as Menus;
          newMenus[item.id] = Object.assign(newMenus[item.id], item);
        } else {
          // 防止js报错
          newMenus[item.parentId] ??= {} as Menus;
          newMenus[item.parentId].children ??= [];
          newMenus[item.parentId].children?.push(item);
        }
      });

      return newMenus;
    },
  },
  actions: {
    updateMenus(menus: Menus[]) {
      this.menus = menus;
    },
    updateUsername(username: string) {
      this.username = username;
    },
  },
});

export const useOutUserStore = () => useUserStore(store);
